﻿using System.Windows.Forms;
using Habanero.Faces.Base;
using Habanero.Faces.Win;
using DialogResult = Habanero.Faces.Base.DialogResult;

namespace FireStarterModeller.UI.Dialogs
{
    public class OpenFileDialogExtendedTextBox : ExtendedTextBoxWin
    {

        private readonly OpenFileDialog _openFileDialog;
        public OpenFileDialogExtendedTextBox() : this(GlobalUIRegistry.ControlFactory)
        {

        }

        public OpenFileDialogExtendedTextBox(IControlFactory controlFactory) : base(controlFactory)
        {
            _openFileDialog = new OpenFileDialog {Multiselect = false};
            this.FileExtensions = new FileExtensionsFilterFormatter();
            this.DefaultExtension = new FileExtensionFilterElement();
            this.Button.Click += (sender, args) => this.ShowDialog();
        }

        public string FileName
        {
            get { return this.TextBox.Text; }
            private set { this.TextBox.Text = value; }
        }
        public FileExtensionsFilterFormatter FileExtensions { get; private set; }
        public FileExtensionFilterElement DefaultExtension { get; set; }
        public string InitialDirectory
        {
            get { return _openFileDialog.InitialDirectory;  }
            set { _openFileDialog.InitialDirectory = value; }
        }

        public void ShowDialog()
        {
            if (!string.IsNullOrEmpty(FileName))
            {
                _openFileDialog.FileName = FileName;
            }
            SetupFileExtensionFilters();
            var result = ShowFileDialog();
            UpdateDialogResult(result);
        }

        protected virtual DialogResult ShowFileDialog()
        {
            return (DialogResult) _openFileDialog.ShowDialog();
        }

        protected virtual void UpdateDialogResult(DialogResult result)
        {
            if (result != DialogResult.OK) return;
            this.FileName = _openFileDialog.FileName;
        }

        private void SetupFileExtensionFilters()
        {
            if (!string.IsNullOrEmpty(this.InitialDirectory)) _openFileDialog.InitialDirectory = this.InitialDirectory;
            if (this.DefaultExtension.IsValid()) this.DefaultExtension.Format();
            this.FileExtensions.Format();
            if (!string.IsNullOrEmpty(this.DefaultExtension.ExtensionFilter))
            {
                _openFileDialog.DefaultExt = this.DefaultExtension.ExtensionFilter;
            }
            _openFileDialog.Filter = this.FileExtensions.ExtensionFilter;
        }
   
    }
}
